package com.zou.uaa.security.config;

import com.zou.uaa.security.handler.FailureHandler;
import com.zou.uaa.security.handler.LoginHandler;
import com.zou.uaa.security.handler.NoAccessDeniedHandler;
import com.zou.uaa.security.handler.SuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SuccessHandler successHandler;
    @Autowired
    private FailureHandler failureHandler;
    @Autowired
    private LoginHandler loginHandler;
    @Autowired
    private NoAccessDeniedHandler noAccessDeniedHandler;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin()
                .loginProcessingUrl("/login").permitAll()
                //json化就把这个打开，如果要测试oauth2.0授权码模式就注释掉
//                .successHandler(successHandler).permitAll()
//                .failureHandler(failureHandler).permitAll()
                .and()
                .logout().logoutSuccessHandler(loginHandler)
                .and()
                //其他接口全部拦截，返回403
                .authorizeRequests()
                .antMatchers("/**").authenticated();

        //访问无权限
        http.exceptionHandling().accessDeniedHandler(noAccessDeniedHandler);
    }
}
